import React, { Component } from 'react'
import styles from './index.module.scss'
import {
  Breadcrumb,
  Divider,
  Form,
  Radio,
  Button,
  DatePicker,
  Alert,
  Table,
  Image,
  Tag,
  Modal,
  message,
} from 'antd'
import { getArticleListApi, delArticleListApi } from 'api/article'
import defaultImg from 'assets/error.png'
import { articleStatus } from 'constan/article'
import {
  EditOutlined,
  DeleteOutlined,
  ExclamationCircleOutlined,
} from '@ant-design/icons'
import Channel from 'components/Channel'
const { RangePicker } = DatePicker

export default class Article extends Component {
  state = {
    channels: [],
    page: 1,
    per_page: 2,
    articles: [],
    total_count: 0,
  }

  // 点击筛选
  onFinish = async ({ status, channel_id, date }) => {
    const params = {} // 传递给后端需要的数据
    // 处理状态
    params.status = status === -1 ? null : status
    // 处理频道
    params.channel_id = channel_id === undefined ? null : channel_id
    if (date) {
      params.begin_pubdate = date[0].format('YYYY-MM-DD')
      params.end_pubdate = date[1].format('YYYY-MM-DD')
    }
    params.page = this.state.page
    params.per_page = this.state.per_page
    // 为什么这个数据放到this上 而没有放到state里 和渲染没有关系的 发请求
    this.params = params

    // 发送请求
    const res = await getArticleListApi(params)
    console.log(res, '文章列表')
    this.setState({
      articles: res.results,
      total_count: res.total_count,
    })
  }

  // 监听页码发生变化
  changePage = async (page) => {
    const res = await getArticleListApi({ ...this.params, page })
    this.setState({ articles: res.results, page: page })
  }

  // 点击删除
  onDel = (id) => {
    Modal.confirm({
      title: '确认框',
      icon: <ExclamationCircleOutlined />,
      content: '您确认删除该文章?',
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        const { articles, page } = this.state
        await delArticleListApi(id)
        message.success('删除成功')
        if (articles.length === 1 && page === 1) {
          return this.setState({ articles: [], total_count: 0, page: 1 })
        }
        // 获取第几页的数据
        // 获取当前页 还是 上一页
        const computedPage = articles.length === 1 ? page - 1 : page
        const res = await getArticleListApi({
          ...this.params,
          page: computedPage,
        })
        this.setState({
          articles: res.results,
          total_count: res.total_count,
          page: computedPage,
        })
      },
    })
  }
  columns = [
    {
      title: '封面',
      dataIndex: 'cover',
      render(cover) {
        if (cover.type !== 0) {
          return (
            <Image
              width={200}
              height={150}
              src={cover.images[0]}
              fallback="http://destiny001.gitee.io/image/none.png"
            />
          )
        }
        return (
          <Image preview={false} width={200} height={150} src={defaultImg} />
        )
      },
      width: 220,
    },
    {
      title: '标题',
      dataIndex: 'title',
    },
    {
      title: '状态',
      dataIndex: 'status',
      render(status) {
        const { color, text } = articleStatus[status]
        return <Tag color={color}>{text}</Tag>
      },
    },
    {
      title: '发布时间',
      dataIndex: 'pubdate',
    },
    {
      title: '阅读数',
      dataIndex: 'read_count',
    },
    {
      title: '评论数',
      dataIndex: 'comment_count',
    },
    {
      title: '点赞数',
      dataIndex: 'like_count',
    },
    {
      title: '操作',
      render: (_, row) => {
        return (
          <>
            <Button
              style={{ marginRight: 10 }}
              type="primary"
              shape="circle"
              icon={<EditOutlined />}
              onClick={() => {
                this.props.history.push('/home/publish/' + row.id)
              }}
            />
            <Button
              onClick={() => {
                this.onDel(row.id)
              }}
              type="danger"
              shape="circle"
              icon={<DeleteOutlined />}
            />
          </>
        )
      },
      width: 110,
    },
  ]
  render() {
    const { total_count, articles, page, per_page } = this.state

    return (
      <div className={styles.article}>
        {/* 面包屑 */}
        <Breadcrumb>
          <Breadcrumb.Item onClick={() => this.props.history.push('/home')}>
            首页
          </Breadcrumb.Item>
          <Breadcrumb.Item>文章管理</Breadcrumb.Item>
        </Breadcrumb>
        <Divider />
        {/* 表单 */}
        <Form
          name="filterArticle"
          onFinish={this.onFinish}
          initialValues={{
            status: -1,
          }}
        >
          <Form.Item label="状态" name="status">
            <Radio.Group>
              <Radio value={-1}>全部</Radio>
              <Radio value={0}>草稿</Radio>
              <Radio value={1}>待审核</Radio>
              <Radio value={2}>审核通过</Radio>
              <Radio value={3}>审核失败</Radio>
            </Radio.Group>
          </Form.Item>

          <Form.Item label="频道" name="channel_id">
            <Channel />
          </Form.Item>

          <Form.Item label="日期" name="date">
            <RangePicker />
          </Form.Item>

          {/* 筛选按钮 */}
          <Form.Item>
            <Button type="primary" htmlType="submit">
              筛选
            </Button>
          </Form.Item>
        </Form>
        {/* 结果提示 */}
        {total_count ? (
          <Alert
            message={`根据筛选条件共查询到${total_count}条结果：`}
            type="success"
          />
        ) : null}
        {/* 表格区域 */}
        <Table
          rowKey="id"
          pagination={{
            current: page,
            total: total_count,
            pageSize: per_page,
            position: ['bottomCenter'],
            onChange: this.changePage,
          }}
          dataSource={articles}
          columns={this.columns}
        />
        ;
      </div>
    )
  }
}
